//
//  WebManager.swift
//  ToBeBigFE
//
//  Created by mingo on 2020/2/24.
//  Copyright © 2020 com.example. All rights reserved.
//

import Foundation
import Alamofire

class WebManager {
    
    // 单例模式
    public static let shared = WebManager()
    
    public let settings = UserDefaults(suiteName: "WebDev")!
    
    private let versionManager = VersionManager(userDefaults: UserDefaults(suiteName: "Web")!)
    private let zipManager = ZipManager()
    
    init() {
        WebOfflineURLProtocol.enableURLProtocol()
    }
    
    func updateManifest(callback: @escaping ManifestUpdatedCallback) {
        versionManager.updateManifest(callback: callback)
    }
    
    func updateProject(id: String) {
        updateManifest() { _ in
            self.updateOfflineZip(id: id) { _ in }
        }
    }
    
    // 根据id和page获取正式的url
    func getWebUrl(id: String, page: String) -> String {
        if isDebugProject(id),
            let server = settings.string(forKey: "server"),
            let project = settings.string(forKey: "project")
        {
            return "http://\(server)/\(project)/dev/\(page)"
        }
        var version = versionManager.getVersion(id: id)
        if version == nil || !zipManager.hasOfflineFiles(id: id, version: version!) {
            version = versionManager.getBuiltinVersion(id: id)
            if (!zipManager.hasOfflineFiles(id: id, version: version!)) {
                zipManager.unzipBuiltin(id: id, version: version!)
            }
        }
        return "\(WebConst.WEB_BASE_URL)\(id)/\(version!)/\(page)"
    }
    
    func getOfflineFile(id: String, version: String, filePath: String) -> String {
        return zipManager.getOfflineFile(id: id, version: version, filePath: filePath)
    }
    
    private func updateOfflineZip(id: String, callback: @escaping OfflineZipUpdatedCallback) {
        if isDebugProject(id) {
            callback(nil)
            return
        }
        if id.isEmpty {
            callback(.argumentError)
            return
        }
        guard let version = versionManager.getVersion(id: id) else {
            callback(.argumentError)
            return
        }
        zipManager.updateOfflineZip(id: id, version: version, callback: callback)
    }
    
    private func isDebugProject(_ id: String) -> Bool {
        if settings.bool(forKey: "enabled"),
            let _ = settings.string(forKey: "server"),
            let project = settings.string(forKey: "project"),
            project == id
        {
            return true
        }
        return false
    }
    
}
